# reference: 20190508_主成分分析_人脸识别.ipynb
import numpy as np
import pandas as pd
import os, sys
from sklearn.decomposition import PCA
from PIL import Image, ImageShow

dataSetsPath = "./data/orl_faces/"
data_dict = {"dirName": [], "dirPath": [], "imgArr":[]}
for ix, file in enumerate(os.walk(dataSetsPath)):
    dir_path, dir_name, content_name = file
    file_name = dir_path.split("/")[-1]
    if 's' in file_name:
        for content in content_name:
            file_dir = dir_path + "/" + content
            tmp_image = Image.open(file_dir)
            img_arr = np.asarray(tmp_image).reshape(1, -1).astype('float').tolist()[0]
            # 存储
            data_dict['dirName'].append(file_name)
            data_dict['dirPath'].append(file_dir.split("/")[-1])
            data_dict['imgArr'].append(img_arr)

data_df = pd.DataFrame(data_dict)
print(data_df.head(5).to_latex())

x_data_arr = np.array(data_dict['imgArr'])
y_data_arr = np.array(data_dict['dirName'])
print(x_data_arr.shape)

label_dict = {value: int(ix+1) for ix, value in enumerate(set(y_data_arr))}
y_data_arr = np.array([label_dict[label] for label in y_data_arr])

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x_data_arr, y_data_arr, test_size=0.20, random_state=42)
print(x_train.shape, x_test.shape)

x_train_mean = x_train.mean(axis=0)
x_train_div = x_train - x_train_mean
x_test_div = x_test - x_train_mean

from sklearn.metrics import precision_score, recall_score
from sklearn.metrics import f1_score
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
import seaborn as sns

n_components = 300
#result_dict['特征向量数量'].append(n_components)
pca_alg = PCA(n_components= n_components)
pca_alg.fit(x_train_div)

import matplotlib.pyplot as plt
plt.plot(range(0, n_components), pca_alg.explained_variance_ratio_, 'r*-')
plt.grid(True)
plt.xlabel("序号")
plt.ylabel("特征值")
plt.savefig("4.10-mainEigen.png")